from django.shortcuts import render
from rest_framework.views import APIView

from apps.logins.serializers import ManagedClassSerializer
from utils.jsonResponse import SuccessResponse, ErrorResponse, DetailResponse
from utils import request_util
from apps.student.models import StudentInfo,ClassInfo
from apps.teacher.models import TeachingInfo, TeacherInfo
from apps.student.serializers import StudentInfoSerializer,StudentIDSerializer
# Create your views here.


class TeacherGetStudentByIdView(APIView):

    def get(self, request, *args, **kwargs):
        print("Request Headers:", request.headers)
        user = request_util.get_request_user(request)
        if not user.is_authenticated:
            return ErrorResponse(msg="用户未登录", code=401)
        # 获取教师管理的班级
        # 初始化一个空列表用于存储所有学生信息
        all_class = []
        if user.role == 1:
            try:
                teacher_info = TeacherInfo.objects.get(UserID=user.id)
            except TeacherInfo.DoesNotExist:
                return ErrorResponse({"msg": "教师信息不存在"}, status=404)
            managed_classes = TeachingInfo.objects.filter(TeacherID=teacher_info.TeacherID)
            # 根据 managedClass.class_id 获取所有学生
            if managed_classes.count() == 0:
                return SuccessResponse(msg="该教师没有任课班级")
            # 遍历所有管理的班级
            for managed_class in managed_classes:
                ClassName = ClassInfo.objects.filter(ClassID=managed_class.ClassID).values("ClassName").first()["ClassName"]
                # 获取班级对应的学生
                students = StudentInfo.objects.filter(ClassName=managed_class.ClassID).values("StudentID","Name").order_by("StudentID")
                # 使用序列化器序列化班级信息
                managed_class_data = ManagedClassSerializer(managed_class).data
                # 创建一个字典，存储班级信息和学生信息
                managed_class_data["className"] = ClassName
                managed_class_data["students"] = StudentIDSerializer(students, many=True).data
                all_class.append(managed_class_data)
        return SuccessResponse(data=all_class)